import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:distribution_mall_flutter/base/base_service.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/dialog/bottom_select_dialog.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/http/modules/common.dart';
import 'package:distribution_mall_flutter/http/modules/merchant_authentication.dart';
import 'package:distribution_mall_flutter/pages/address/address_area_select.dart';
import 'package:distribution_mall_flutter/pages/merchant_authentication/merchant_authentication_provider.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_utils.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:phone_numbers_parser/phone_numbers_parser.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:image_picker/image_picker.dart';

import '../../../http/init.dart';

part 'merchant_authentication_service.g.dart';

class MerchantAuthenticationService extends BaseService {
  MerchantAuthenticationService(super.ref);

  Future<void> queryLast() async {
    (await MerchantAuthenticationApi.queryLast()).yes((value) {
      // value?.auditState = 'REJECT';
      // value?.rejectReason = 'REJECT';
      ref.read(merchantAuthenticationProvider.notifier).setNewData(value);
    });
  }

  Future<void> selectPic() async {
    int? index = await showModalBottomSheet(
        context: appRouter.navigatorKey.currentContext!,
        builder: (_) => BottomSelectDialog(
              content: [S.current.camera, S.current.gallery],
            ));
    if (index == null) {
      return;
    }
    XFile? file = await ImagePicker().pickImage(
        source: index == 0 ? ImageSource.camera : ImageSource.gallery);
    if (file != null) {
      ref
          .read(merchantAuthenticationSelectImageFileShowErrorProvider.notifier)
          .setError(false);
      ref
          .read(merchantAuthenticationSelectImageFileProvider.notifier)
          .setNewData(file);
    }
  }

  Future<void> commit({
    required String businessName,
    required String certificateNo,
    required String tel,
    required String? detailed,
  }) async {
    var telParse = PhoneNumber.parse(Utils.addPrePhone(tel, plusSymbol: false));
    // println('telParse ${telParse}');
    // return;
    var merchantAuthenticationState = ref.read(merchantAuthenticationProvider);
    String? link;

    ///如果是被拒
    if (merchantAuthenticationState.merchantAuthLastBody?.auditState ==
            'REJECT' &&
        ref.read(merchantAuthenticationSelectImageFileProvider) == null) {
      link =
          merchantAuthenticationState.merchantAuthLastBody!.businessPermitUrl!;
    } else {
      var file = ref.read(merchantAuthenticationSelectImageFileProvider);
      if (file != null) {
        if (kIsWeb) {
          link = (await CommonApi.uploadSingleFile(
              file: await UploadFileInfo.fromBytes(
                  bytes: await ImageUtils.webCompressImage(
                      await file.readAsBytes(),
                      path: file.path),
                  path: file.path)));
        } else {
          link = (await CommonApi.uploadSingleFile(
              file: UploadFileInfo.fromPath(
                  file: await ImageUtils.compressFile(File(file.path), 60))));
        }
      }
    }
    if (link != null) {
      ///上传成功后
      (await MerchantAuthenticationApi.apply(
        businessName: businessName,
        certificateNo: certificateNo,
        businessPermitUrl: link,
        countryCode: telParse.countryCode,
        callingNumber: tel,
        country: NationCode.ph,
        province: province ??
            merchantAuthenticationState.merchantAuthLastBody?.address?.province,
        city: city ??
            merchantAuthenticationState.merchantAuthLastBody?.address?.city,
        district: district ??
            merchantAuthenticationState.merchantAuthLastBody?.address?.district,
        street: street ??
            merchantAuthenticationState.merchantAuthLastBody?.address?.street,
        detailed: detailed ??
            merchantAuthenticationState.merchantAuthLastBody?.address?.detailed,
      ))
          .yes((value) {
        ref
            .read(merchantAuthenticationSelectImageFileProvider.notifier)
            .setNewData(null);

        ///查询最新状态
        queryLast();
        FirebaseAnalyticsUtils.logEvent(
            name: PointConstant.merchantAuthenticationSubmit,
            parameters: {'success': 1});
      }).no((err) {
        FirebaseAnalyticsUtils.logEvent(
            name: PointConstant.merchantAuthenticationSubmit,
            parameters: {'success': 0});
      });
    }
  }

  ///选择的
  String? city, province, district, street, virtualPostcode;

  void selectAddress(BuildContext context) {
    showModalBottomSheet(
        context: context,
        enableDrag: false,
        isScrollControlled: true,
        builder: (_) => AddressAreaSelect(
              callback: (list) {
                // LogUtil.d(list);
                // LogUtil.d(list.length);
                virtualPostcode = list.last.virtualPostcode;
                city = list[1].name;
                province = list[0].name;
                district = list[2].name;
                street = list[3].name;
                ref
                    .read(merchantAuthenticationProvider)
                    .addressController
                    .text = list.map((e) => e.name).join('/');
                //
                // _formKey.currentState!.fields['address']!
                //     .didChange(list
                //     .map((e) => e.name)
                //     .join('/'));
                // _formKey.currentState!.fields['zip']!
                //     .didChange(list.last.postcode ?? '');
                Navigator.pop(context);
              },
            ));
  }
}

@riverpod
MerchantAuthenticationService merchantAuthenticationService(
    MerchantAuthenticationServiceRef ref) {
  return MerchantAuthenticationService(ref);
}
